from flask import render_template,redirect,url_for,session, flash, request, jsonify
from flask_login import login_required, current_user
#from flaskext.uploads import UploadSet, IMAGES

from werkzeug.utils import secure_filename

from controller import app
from lib.form import Form
from dao.item import ItemDao
from model.item import Item
from model.picture import Picture
from service.picture import PictureService
from dao.picture import PictureDao

from service.item import ItemValidator

from core import user_permission


IMAGES = tuple('jpg jpe jpeg png gif svg bmp'.split())

class ItemsForm(Form):
    def __init__(self):
        '''Only accept POST request
        '''
        Form.__init__(self)

class ItemForm(Form):
    def __init__(self):
        '''Only accept POST request
        '''
        Form.__init__(self)
        if self.is_submitted():
            # If get fail, return None
            self.action = self.request.values.get('item-action')
            if self.action == 'edit-item':
                self.id = self.request.values.get('item-id')
            else:
                self.id = None
                
            self.name = self.request.values.get('item-name')
            
            _type = self.request.values.get('item-type')
            if _type == 'Item':
                self.type = 0
            elif _type == 'Service':
                self.type = 1
                
            self.price = float(self.request.values.get('price'))
            
            if self.type == 0:
                self.quantity = int(self.request.values.get('quantity'))
            else:
                self.quantity = 1
                
            self.description = self.request.values.get('item-description')
            
            self.status = 0


@app.errorhandler(403)
def page_not_found(e):
    session['redirected_from'] = request.url
    return redirect(url_for('login'))

            
@app.route('/validate_item')
@app.route('/validate_item', methods=['GET','POST'])
@login_required
def validate_item():
    values = {}
    if request.values['page'] == '0':
        for key in request.values:
            values[key] = request.values[key]
    
    v = ItemValidator()
    ret = v.validate(values)
    return jsonify(errors=ret)

@user_permission.require(http_exception=403)        
@app.route('/manage_items')
@app.route('/manage_items', methods=['GET','POST'])
@login_required
def manage_items():
    #form = ItemForm()
    #item_dao = ItemDao()
    return redirect(url_for('display_items'))

@app.route('/display_items')
@login_required
def display_items():
    #return render_template("add_item-v1.html", items=None)
    return render_template("manage_items.html", items=None, pictures=None)
    
@app.route('/edit_item')
@login_required
def edit_item():
    item_dao = ItemDao()
    _items = item_dao.filter_by(user_id=current_user.get_id())
    return render_template("items.html", items=_items)
    
@app.route("/delete_items", methods=["GET", "POST"])
@login_required
def delete_items():
    item_dao = ItemDao()
    
    form = ItemsForm()
    ids = form.request.form.getlist('selected')
    for _id in ids:
        item = item_dao.filter_first(id=int(_id))
        picture_service = PictureService(item)
        picture_service.delete_pictures()
        
        item_dao.remove_item(item)
        
    return render_template("manage_items.html", items=item_dao.filter_by(user_id=current_user.id))            
